import React, { useEffect, useRef, useState } from "react";
import { useParams, useNavigate } from "react-router";
import { getSongDetail, getSongUrl, getLyric, getComment } from "@/api/details";
import { Card, Avatar, List, Badge, Input } from "antd";
import {
  AlignLeftOutlined,
  PlayCircleOutlined,
  DownloadOutlined,
} from "@ant-design/icons";
import { setSongInfo } from "@/store/modules/songInfo";
import { useDispatch, useSelector } from "react-redux";

export default function SongDetails() {
  const navigate = useNavigate()
  const toList = () => {
    navigate(-1);
  };
  const { Meta } = Card;
  const { TextArea } = Input;
  const { id } = useParams();
  const { songInfo } = useSelector((state) => state.songInfoSlice);

  const urlRef = useRef();
  const lrcRef = useRef();

  const [comments, setComments] = useState([]);
  const [hotComments, setHotComments] = useState([]);

  const dispatch = useDispatch();
  const getSongInfo = async () => {
    // 获取播放链接
    await getSongUrl({ id, level: "standard" }).then((res) => {
      urlRef.current = res?.data?.data?.[0].url;
      localStorage.setItem('songId',id)   //将歌曲ID存入本地存储
      getLyric({ id }).then((res) => {
        lrcRef.current = res?.data?.lrc?.lyric;
        // 根据动态路由传递过来ID获取歌名,封面,作者
        getSongDetail({ ids: id }).then((res) => {
          dispatch(
            setSongInfo({
              // 歌名
              name: res?.data?.songs?.[0]?.al?.name,
              // 封面
              cover: res?.data?.songs?.[0]?.al?.picUrl,
              // 作者
              artist: res?.data?.songs?.[0]?.ar
                .map((item) => {
                  return item?.name;
                })
                .join(","),
              url: urlRef.current,
              lrc: lrcRef.current,
            })
          );
        });
      });
    });
  };

  const handleGetComment = () => {
    getComment({ id }).then(res => {
      setComments(res.data.comments)
      setHotComments(res.data.hotComments);
    })
  }
  useEffect(() => {
    getSongInfo();
    handleGetComment();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onPressEnter = e => {
    console.log(e.target.value);
  }
  return (
    <>
      <button style={{ width: 60, height: 30, margin: 10 }} onClick={toList}>返回</button>
      <Card
        style={{
          margin: "0 auto",
          width: 600,
        }}
        cover={<img alt={urlRef.current} src={songInfo?.cover} />}
        actions={[
          <PlayCircleOutlined key="play" />,
          <DownloadOutlined key="download" />,
          <a href="#comments">
            <AlignLeftOutlined key="ellipsis" />
          </a>,
        ]}
      >
        <Meta
          title={`歌名:${songInfo?.name}`}
          description={`作者列表:${songInfo?.artist}`}
        />
      </Card>
      {/* 输入评论 */}
      <TextArea
        autoSize={{ minRows: 2, maxRows: 5 }}
        allowClear
        onPressEnter={onPressEnter}
        showCount
      />
      {/* 热评列表 */}
      <Badge.Ribbon text="热评列表" color="red" style={{ marginRight: "10px" }}>
        <List
          header={
            <h3>热评({hotComments.length ? hotComments.length : "暂无"})</h3>
          }
          style={{ margin: "0 20px" }}
          itemLayout="horizontal"
          dataSource={hotComments}
          renderItem={(item) => (
            <List.Item>
              <List.Item.Meta
                avatar={<Avatar src={item.user.avatarUrl} />}
                title={<a href="https://ant.design">{item.user.nickname}</a>}
                description={item.content}
              />
              <div>{item.timeStr}</div>
              <div>{item.ipLocation.location}</div>
            </List.Item>
          )}
        />
      </Badge.Ribbon>
      {/* 评论列表 */}
      <List
        id="comments"
        header={<h3>评论({comments.length})</h3>}
        style={{ margin: "0 20px" }}
        itemLayout="horizontal"
        dataSource={comments}
        renderItem={(item) => (
          <List.Item>
            <List.Item.Meta
              avatar={<Avatar src={item.user.avatarUrl} />}
              title={<a href="https://ant.design">{item.user.nickname}</a>}
              description={item.content}
            />
            <div>{item.timeStr}</div>
            <div>{item.ipLocation.location}</div>
          </List.Item>
        )}
      />
    </>
  );
}
